JavaScript syntax
part 35/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
// It can be used multiple times in the same expression
const b = [...a, ...a]; // b = [1, 2, 3, 4, 1, 2, 3, 4];
// It can be combined with non-spread items.
const c = [5, 6, ...a, 7, 9]; // c = [5, 6, 1, 2, 3, 4, 7, 9];
// For comparison, doing this without the spread operator
// creates a nested array.
const d = [a, a]; // d = [[1, 2, 3, 4], [1, 2, 3, 4]]
// It works the same with function calls
function foo(arg1, arg2, arg3) {
console.log(`${arg1}:${arg2}:${arg3}`);
}
// Users can use it even if it passes more parameters than the function will use
foo(...a); // "1:2:3" → foo(a[0], a[1], a[2], a[3]);
// Users can mix it with non-spread parameters
foo(5, ...a, 6); // "5:1:2" → foo(5, a[0], a[1], a[2], a[3], 6);
// For comparison, doing this without the spread operator
// assigns the array to arg1, and nothing to the other parameters.
foo(a); // "1,2,3,4:undefined:undefined"
const bar = { a: 1, b: 2, c: 3 };
// This would copy the object
const copy = { ...bar }; // copy = { a: 1, b: 2, c: 3 };
// "b" would be overridden here
const override = { ...bar, b: 4 }; // override = { a: 1, c: 3, b: 4 }
When ... is used in a function declaration, it indicates a rest parameter. The rest parameter must be the final named parameter in the function's parameter list. It will be assigned an Array containing any arguments passed to the function in excess of the other named parameters. In other words, it gets "the rest" of the arguments passed to the function (hence the name).
function foo(a, b, ...c) {
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────